package br.com.infnet.formularioeletronico.visao;

import br.com.infnet.formularioeletronico.dados.CursoDAO;
import br.com.infnet.formularioeletronico.interfaces.ICursoDAO;
import br.com.infnet.formularioeletronico.modelo.Curso;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;
import javax.swing.*;

public class TelaCursos extends javax.swing.JFrame {

    /**
     *
     */
    private static final long serialVersionUID = -2546263461845289454L;
    private int numberOfEntries = 0;
    private int currentEntryIndex;
    private Curso currentEntry;
    private List< Curso> results;
    private JPanel painelNavegacao;
    private JButton browseButton;
    private JLabel descricaoLabel;
    private JTextField descricaoTextField;
    private JLabel idLabel;
    private JTextField idTextField;
    private JTextField indexTextField;
    private JTextField maxTextField;
    private JCheckBox statusCheckBox;
    private JButton proximoButton;
    private JLabel deLabel;
    private JButton anteriorButton;
    private JButton queryButton;
    private JLabel queryLabel;
    private JPanel queryPanel;
    private JPanel displayPanel;
    private JTextField queryTextField;
    private JButton insertButton;

    /**
     * Create the frame.
     */
    public TelaCursos() {
        // create GUI
        painelNavegacao = new JPanel();
        painelNavegacao.setBounds(86, 10, 222, 23);
        anteriorButton = new JButton();
        indexTextField = new JTextField(2);
        indexTextField.setSize(21, 23);
        deLabel = new JLabel();
        maxTextField = new JTextField(2);
        proximoButton = new JButton();
        displayPanel = new JPanel();
        displayPanel.setBounds(86, 43, 222, 93);
        idLabel = new JLabel();
        idLabel.setBounds(0, 11, 86, 20);
        idTextField = new JTextField(10);
        idTextField.setBounds(90, 11, 45, 20);
        descricaoLabel = new JLabel();
        descricaoLabel.setBounds(0, 33, 86, 20);
        descricaoTextField = new JTextField(10);
        descricaoTextField.setBounds(90, 33, 132, 20);
        queryPanel = new JPanel();
        queryPanel.setBounds(78, 148, 235, 50);
        queryLabel = new JLabel();
        queryTextField = new JTextField(10);
        queryButton = new JButton();
        setSize(400, 270);
        setResizable(false);

        painelNavegacao.setLayout(new BoxLayout(painelNavegacao, BoxLayout.X_AXIS));

        anteriorButton.setText(" Ant ");
        anteriorButton.setEnabled(false);
        anteriorButton.addActionListener(
                new ActionListener() {

            @Override
                    public void actionPerformed(ActionEvent evt) {
                        previousButtonActionPerformed(evt);
                    }
                });

        painelNavegacao.add(anteriorButton);
        painelNavegacao.add(Box.createHorizontalStrut(10));

        indexTextField.setHorizontalAlignment(JTextField.CENTER);
        indexTextField.addActionListener(
                new ActionListener() {

            @Override
                    public void actionPerformed(ActionEvent evt) {
                        indexTextFieldActionPerformed(evt);
                    }
                });

        painelNavegacao.add(indexTextField);
        painelNavegacao.add(Box.createHorizontalStrut(5));

        deLabel.setText("de");
        painelNavegacao.add(deLabel);
        painelNavegacao.add(Box.createHorizontalStrut(5));

        maxTextField.setHorizontalAlignment(JTextField.CENTER);
        maxTextField.setEditable(false);
        painelNavegacao.add(maxTextField);
        painelNavegacao.add(Box.createHorizontalStrut(5));

        proximoButton.setText(" Prox ");
        proximoButton.setEnabled(false);
        proximoButton.addActionListener(
                new ActionListener() {

            @Override
                    public void actionPerformed(ActionEvent evt) {
                        nextButtonActionPerformed(evt);
                    }
                });
        getContentPane().setLayout(null);

        painelNavegacao.add(proximoButton);
        getContentPane().add(painelNavegacao);
        displayPanel.setLayout(null);

        idLabel.setText("ID:");
        displayPanel.add(idLabel);

        idTextField.setEditable(false);
        displayPanel.add(idTextField);

        descricaoLabel.setText("Descri\u00E7\u00E3o:");
        displayPanel.add(descricaoLabel);
        displayPanel.add(descricaoTextField);
        getContentPane().add(displayPanel);

        statusCheckBox = new JCheckBox("Status");
        statusCheckBox.setBounds(90, 56, 97, 23);
        displayPanel.add(statusCheckBox);

        queryPanel.setLayout(new BoxLayout(queryPanel, BoxLayout.X_AXIS));
        queryPanel.setBorder(BorderFactory.createTitledBorder("Buscar curso pela descrição"));
        queryLabel.setText("Descri\u00E7\u00E3o:");
        queryPanel.add(Box.createHorizontalStrut(5));
        queryPanel.add(queryLabel);
        queryPanel.add(Box.createHorizontalStrut(10));
        queryPanel.add(queryTextField);
        queryPanel.add(Box.createHorizontalStrut(10));

        queryButton.setText("OK");
        queryButton.addActionListener(
                new ActionListener() {

            @Override
                    public void actionPerformed(ActionEvent evt) {
                        try {
                            queryButtonActionPerformed(evt);
                        } catch (SQLException e) {
                        }
                    }
                });

        queryPanel.add(queryButton);
        queryPanel.add(Box.createHorizontalStrut(5));
        getContentPane().add(queryPanel);
        browseButton = new JButton();
        browseButton.setBounds(72, 207, 77, 23);

        browseButton.setText("List");
        browseButton.addActionListener(
                new ActionListener() {

            @Override
                    public void actionPerformed(ActionEvent evt) {
                        browseButtonActionPerformed(evt);
                    }
                });

        getContentPane().add(browseButton);

        insertButton = new JButton();
        insertButton.setBounds(159, 207, 77, 23);
        insertButton.setText("Insert");
        insertButton.addActionListener(
                new ActionListener() {

            @Override
                    public void actionPerformed(ActionEvent evt) {
                        insertButtonActionPerformed(evt);
                    }
                });
        getContentPane().add(insertButton);

        JButton updateButton = new JButton();
        updateButton.setBounds(246, 207, 77, 23);
        updateButton.setText("Update");
        updateButton.addActionListener(
                new ActionListener() {

            @Override
                    public void actionPerformed(ActionEvent evt) {
                        updateButtonActionPerformed(evt);
                    }
                });
        getContentPane().add(updateButton);

        setTitle("Tela de Cursos");
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public static void main(String args[]) {
        new TelaCursos();
    }

    private void previousButtonActionPerformed(ActionEvent evt) {
        currentEntryIndex--;

        if (currentEntryIndex < 0) {
            currentEntryIndex = numberOfEntries - 1;
        }

        indexTextField.setText("" + (currentEntryIndex + 1));
        indexTextFieldActionPerformed(evt);
    }

    private void nextButtonActionPerformed(ActionEvent evt) {
        currentEntryIndex++;

        if (currentEntryIndex >= numberOfEntries) {
            currentEntryIndex = 0;
        }

        indexTextField.setText("" + (currentEntryIndex + 1));
        indexTextFieldActionPerformed(evt);
    }

    private void indexTextFieldActionPerformed(ActionEvent evt) {
        currentEntryIndex = (Integer.parseInt(indexTextField.getText()) - 1);

        if (numberOfEntries != 0 && currentEntryIndex < numberOfEntries) {
            currentEntry = results.get(currentEntryIndex);

            idTextField.setText("" + currentEntry.getId());
            descricaoTextField.setText(currentEntry.getDescricao());

            if (currentEntry.getStatus().equalsIgnoreCase("S")) {
                statusCheckBox.setSelected(true);
            } else {
                statusCheckBox.setSelected(false);
            }

            maxTextField.setText("" + numberOfEntries);
            indexTextField.setText("" + (currentEntryIndex + 1));
        }
    }

    private void insertButtonActionPerformed(ActionEvent evt) {
        if (validarCamposObrigatoriosInclusao()) {

            ICursoDAO objCursoDAO = new CursoDAO();
            long result = objCursoDAO.incluir(new Curso(descricaoTextField.getText(),
                    (statusCheckBox.isSelected() ? "S" : "N")));

            if (result > 0) {
                JOptionPane.showMessageDialog(this, "Curso incluído!", "Inclusão de curso", JOptionPane.PLAIN_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Curso não incluído!", "Erro", JOptionPane.PLAIN_MESSAGE);
            }

            browseButtonActionPerformed(evt);
        }

    }

    private void updateButtonActionPerformed(ActionEvent evt) {
        if (validarCamposObrigatorios()) {

            if (idTextField.getText().length() == 0) {
                JOptionPane.showMessageDialog(this, "Selecione um curso!", "Atualização de curso", JOptionPane.WARNING_MESSAGE);
            } else {
                ICursoDAO objCursoDAO = new CursoDAO();
                boolean result = objCursoDAO.alterar(new Curso(Long.parseLong(idTextField.getText()),
                        descricaoTextField.getText(),
                        (statusCheckBox.isSelected() ? "S" : "N")));

                if (result) {
                    JOptionPane.showMessageDialog(this, "Curso alterado!", "Atualização de curso", JOptionPane.PLAIN_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "Curso não alterado!", "Erro", JOptionPane.PLAIN_MESSAGE);
                }

                browseButtonActionPerformed(evt);
            }

        }

    }

    private void browseButtonActionPerformed(ActionEvent evt) {
        try {

            ICursoDAO objCursoDAO = new CursoDAO();
            results = objCursoDAO.listar();
            numberOfEntries = results.size();

            if (numberOfEntries != 0) {
                currentEntryIndex = 0;
                currentEntry = results.get(currentEntryIndex);

                idTextField.setText("" + currentEntry.getId());
                descricaoTextField.setText(currentEntry.getDescricao());

                if (currentEntry.getStatus().equalsIgnoreCase("S")) {
                    statusCheckBox.setSelected(true);
                } else {
                    statusCheckBox.setSelected(false);
                }

                maxTextField.setText("" + numberOfEntries);
                indexTextField.setText("" + (currentEntryIndex + 1));

                proximoButton.setEnabled(true);
                anteriorButton.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(this, "Não há cursos cadastrados!", "Listar cursos", JOptionPane.WARNING_MESSAGE);
                idTextField.setText("");
                descricaoTextField.setText("");
                statusCheckBox.setSelected(false);
            }
        } catch (Exception e) {
        }
    }

    private void queryButtonActionPerformed(ActionEvent evt) throws SQLException {
        ICursoDAO objCursoDAO = new CursoDAO();
        results = objCursoDAO.listar("descricao", queryTextField.getText().toUpperCase());
        numberOfEntries = results.size();

        if (numberOfEntries != 0) {
            currentEntryIndex = 0;
            currentEntry = results.get(currentEntryIndex);

            idTextField.setText("" + currentEntry.getId());
            descricaoTextField.setText(currentEntry.getDescricao());

            if (currentEntry.getStatus().equalsIgnoreCase("S")) {
                statusCheckBox.setSelected(true);
            } else {
                statusCheckBox.setSelected(false);
            }

            maxTextField.setText("" + numberOfEntries);
            indexTextField.setText("" + (currentEntryIndex + 1));

            proximoButton.setEnabled(true);
            anteriorButton.setEnabled(true);
        } else {
            JOptionPane.showMessageDialog(this, "Não foi encontrado nenhum curso com o critério especificado!", "Pesquisa de curso", JOptionPane.WARNING_MESSAGE);
            browseButtonActionPerformed(evt);
        }
    }

    private boolean validarCamposObrigatorios() {

        if (idTextField.getText().length() == 0) { //Verifica se foi preenchido o campo ID
            JOptionPane.showMessageDialog(this, "ID deve ser preenchido!", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;
        } else if (descricaoTextField.getText().length() == 0) { //Verifica se foi preenchido o campo DESCRIÇÃO
            JOptionPane.showMessageDialog(this, "DESCRIÇÃO deve ser preenchido!", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        return true;
    }

    private boolean validarCamposObrigatoriosInclusao() {

        if (descricaoTextField.getText().length() == 0) { //Verifica se foi preenchido o campo DESCRIÇÃO
            JOptionPane.showMessageDialog(this, "DESCRIÇÃO deve ser preenchido!", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        return true;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
